import { defineStore } from 'pinia'
import { getInfo, logout } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => initState(),
  getters: {
    isAuthenticated: (state) => state.token !== '',
  },
  actions: {
    async userLogin(userInfo) {
      try {
        const response = await login(userInfo)
        if (response.errno !== 0) {
          // 登录失败
          console.log('login fail : ', response.err_msg)
          return false
        }
        this.token = response.data.token
        return true
      } catch (err) {
        this.err_msg = err.message
        console.log('login error :', err)
        return false
      } finally {
      }
    },
    async getUserInfo() {
      const response = await getInfo()
      if (!response.data) {
        throw new Error('Verification failed, please Login again.')
      }
      const { roles, name, avatar } = response.data
      this.roles = roles
      this.name = name
      this.avatar = avatar
    },
    async userLogout() {
      await logout()
      // removeToken()
      // this.$reset()
      // resetRouter()
    },
    resetToken() {
      // removeToken()
      // this.$reset()
    },
  },
})

function initState() {
  return {
    token: '',
    name: '',
    avatar: '', // 头像
    data: [],
    errno: 500,
    err_msg: '',
  }
}
